<template>
  <div class="smart-clip">
    <div class="flex justify-between" style="height: 32px; line-height: 32px;">
      <RouteTitle :isBack="true" />
      <a-button type="primary" @click="toViewList">提取记录</a-button>
    </div>
    <div class="ai-wirting mt-20">
      <a-card>
        <a-form layout="horizontal">
          <a-form-item label="视频来源">
            <a-radio-group v-model:value="radioValue">
              <a-radio :value="1"> 网络视频 </a-radio>
              <a-radio :value="2"> 素材库视频 </a-radio>
            </a-radio-group>
          </a-form-item>
          <div class="tip text-gray-5"  v-if="radioValue == 1">
              输入视频分享链接，一键智能视频解析，提取视频。支持平台：{{pList.join('、')}}。
            </div>
          <a-form-item label="视频链接" v-if="radioValue == 1">
           
            <a-textarea v-model:value="internetVideoUrl" placeholder="请粘贴抖音视频链接，视频时长建议不超过20分钟" style="
                width: 450px;
                height: 100px;
                resize: none;
                border-radius: 5px;
              "></a-textarea>
          </a-form-item>
          <a-form-item label="视频素材" v-if="radioValue == 2">
            <a-card v-if="!currentVideo?.material_url">
              <div class="upload-wrapper">
                <div class="upload-content" @click="debouncedClick">
                  <cloud-upload-outlined />
                  <span class="text-16 text-gray-5">添加视频</span>
                </div>
              </div>
            </a-card>
            <div class="video_con" v-else>
              <video id="videoPlayer" :src="currentVideo?.material_url" autoplay />
              <div class="operate_con">
                <cu-icon @click="deleteVideo" type="icon-shanchu1" class="delete_icon" />
              </div>
            </div>
          </a-form-item>
        </a-form>
        <div style="margin-left: 70px">
          <a-button type="primary" :loading="submitLoading" @click="handleExtract">开始提取</a-button>
          <div class="mt-5" style="color:#666">
            当前剩余{{ name_unit }}{{ residue_count
            }}{{ unit }},（每分钟消耗{{ consumes }}{{ unit }}{{ name_unit }},
            不足1分钟按1分钟计算）
          </div>
        </div>
      </a-card>
    </div>
    <ChooseMaterial :isClip="false" material_type="video" :visible="chooseVisible" @close="closeChoose" />

    <!-- <newChooseMaterial
    :isClip="true"
    :visible="chooseVisible"
    modelType = "video"
    @close="closeChoose"
    /> -->

    <notTextSpeech 
    :consumes="consumes" :name_unit="name_unit" :usable="usable"
     :useNum="useNum" :unit="unit"
      @handleOk="handleOk" ref="notVoiceNumDialogRef">
    </notTextSpeech>
  </div>

  <!-- 充值弹窗 -->
  <vipModal :visible="vipVisible" @close="vipVisible = false"></vipModal>

</template>

<script>
import {
  reactive,
  toRefs,
  watch,
  computed,
  ref,
  watchEffect,
  nextTick,
  onUnmounted,
  onMounted
} from "vue";
// 充值弹窗
import vipModal from '@/socialMedia/Vip/vipModal.vue'
const vipModalRef = ref(null)
const vipVisible = ref(false)
import { CloudUploadOutlined, PlusOutlined } from "@ant-design/icons-vue";
import request from "../../../common/utils/request";
import { useRouter } from "vue-router";
import ChooseMaterial from "../EditingCenter/modules/bottomSet/components/chooseMaterial.vue";
import notTextSpeech from "@/views/shotstack/CreationCenter/components/notTextSpeech.vue";
import store from "@/store/index.js";
import utils from '@/common/utils/utils'
import { platformList } from "./utils/index.js";
import { message, notification } from "ant-design-vue";
export default {
  name: "AddVideoToText",
  components: {
    CloudUploadOutlined,
    PlusOutlined,
    notTextSpeech,
    ChooseMaterial,
    vipModal,
  },
  setup() {
    const router = useRouter();
    const state = reactive({
      internetVideoUrl: "",
      radioValue: 1,
      addVisible: false,
      chooseVisible: false,
      currentVideo: {},
      submitLoading: false,
      residue_count: 0,
      debounceTimer: null,
      unit: "",
      name_unit: "",
      consumes: "",
      notVoiceNumDialogRef: null,
      usable: 1,
      vipVisible: false,
      useNum:1,
      pList:platformList,
    });
    const toViewList = () => {
      router.push({ name: "VideoToTextList" });
    }
    // 开始提取
    const handleExtract = async() => {
      if (store.getters.isVersionExpired) {
        notification.warn({ message: "您的套餐已到期", duration: 2 });
          state.vipVisible = true;
        return
      } 
        if (state.radioValue == 1 && !state.internetVideoUrl) {
          message.warn("请先粘贴视频链接");
          return;
        }

        if (
          state.radioValue == 2 &&
          JSON.stringify(state.currentVideo) == "{}"
        ) {
          message.warn("请先从素材库选择视频");
          return;
      }

      // 素材库选择的素材, 可以拿到时长
      if (state.radioValue == 2) {
        try {
          const number = utils.getT(state.currentVideo?.material_duration) 
          const res = await utils.videoConverTextConfig({
            number
          })
          // 查询积分, 积分不足则走不到这一步
          // 获取积分消耗提示内容
          const content = utils.useText(res)
          try {
            // 确认消耗
            await utils.kd({ content,res })
          } catch (error) {
            return
          }
        } catch (error) {
          // 打开充值, 接着打开点数购买
          vipVisible.value = true
          vipModalRef.value && vipModalRef.value.openBuyVisible()
          return
        }
      }
      add()
    };

    const add = async () => {
      state.submitLoading = true;
      let params = {
        script_typeuser: "user",
        video_source: state.radioValue == 1 ? "internet" : "material",
        video_url:
          state.radioValue == 1
            ? state.internetVideoUrl
            : state.currentVideo?.material_url,
        merchant_folder_statck_multimedia_id:
          state.radioValue == 1
            ? 0
            : state.currentVideo?.merchant_folder_statck_id,
      };
      request
        .post("/work_ai", "/user/shotstack/video/conver/text/add", params)
        .then((res) => {
          if (res.id) {
            message.success("创建成功！");
            state.submitLoading = false;

            router.push("VideoToTextList");
          } else {
            state.internetVideoUrl = "";
          }
        })
        .catch((err) => {
          state.submitLoading = false;
        });
    }

    const handleOk = () => {
      add()
    }

    const showOpenMaterialModal = () => {
      state.chooseVisible = true;
    };
    const closeChoose = (obj) => {
      console.log(obj,'选择的素材');
      
      state.chooseVisible = false;
      if (obj) {
        state.currentVideo = obj;
      }
    };

    const playVideo = () => {
      document.getElementById("videoPlayer").play();
    };

    const deleteVideo = () => {
      state.currentVideo = {};
      store.dispatch('setExtractTextData',{})
    };

    const getCount = async(data={}) => {
      const { number = 1, init = false } = data
      return new Promise(async (resolve, reject) => {
        const res =await  request
            .get("/work_ai", "/user/shotstack/video/conver/text/config", {
              number,
            })
        console.log(res.usable, "res接口传参1231312321");
              state.residue_count = res.pointInfo.current;
              state.consumes = res.pointInfo.consumes;
              state.unit = res.pointInfo.unit;
              state.name_unit = res.pointInfo.name;
              // 剩余次数
              state.useNum = res.pointInfo.current
              state.usable = res.usable
              if (res.usable != 1 && !init) {
                state.vipVisible = true;
                reject(false)
                return
              }
              if (!init) {
                state.usable = res.usable
                state.notVoiceNumDialogRef.showModal();
                resolve(true)
              }
      });
    };

    getCount({
      number: 1,
      init:true
    });

    // 防抖
    const debouncedClick = () => {
      if (store.getters.isVersionExpired) {
        notification.warn({ message: "您的套餐已到期", duration: 2 });
        state.vipVisible = true;

      } else {
        if (state.debounceTimer) {
          clearTimeout(state.debounceTimer);
        }

        state.debounceTimer = setTimeout(() => {
          showOpenMaterialModal();
        }, 500);
      }
    };

    onMounted(()=>{
      if(Object.keys(store.getters.extractTextData).length){
        state.currentVideo = store.getters.extractTextData
        state.radioValue = 2
      }
    })

    onUnmounted(() => {
      if (state.timeoutId) {
        clearTimeout(state.timeoutId);
        state.timeoutId = null;
      }
    });

    return {
      ...toRefs(state),
      vipModalRef,
      vipVisible,
      debouncedClick,
      handleOk,
      add,
      showOpenMaterialModal,
      closeChoose,
      handleExtract,
      playVideo,
      deleteVideo,
      toViewList,
    };
  },
};
</script>

<style lang="less" scoped>
.video_con {
  width: 150px;
  height: 250px;
  background-color: #000;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;

  .operate_con {
    display: none;
  }

  &:hover {
    .operate_con {
      width: 150px;
      height: 250px;
      position: absolute;
      left: 0;
      top: 0;
      background-color: rgba(0, 0, 0, 0.3);
      display: flex;
      align-items: center;
      justify-content: center;

      .play_icon {
        color: #fff;
        font-size: 24px;
        cursor: pointer;

        &:hover {
          color: #ff5652;
        }
      }

      .delete_icon {
        color: #fff;
        font-size: 24px;
        cursor: pointer;

        &:hover {
          color: #ff5652;
        }
      }
    }
  }

  video {
    max-width: 100%;
    max-height: 100%;
  }
}

.smart-clip {
  padding: 14px 14px 0;
  height: 100%;
  box-sizing: border-box;
}

.ant-input-number {
  border-radius: 5px;
}

button {
  border-radius: 5px;
}

:deep(.ant-select-selector) {
  border-radius: 0 5px 5px 0 !important;
}

.textarea-wrapper {
  border-radius: 5px;
}

input {
  border-radius: 5px;
}

:deep(.ant-card) {
  border-radius: 15px;
}

.upload-wrapper {
  width: 200px;
  height: 324px;
  margin: 0 20px 20px 0;
  padding: 20px;
  background-color: #f3f4f6;
  border-radius: 15px;
}

.upload-content {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  font-size: 46px;
  width: 160px;
  height: 284px;
  background-color: #fff;
  border-radius: 15px;
  cursor: pointer;
}

.text-16 {
  font-size: 16px;
}
.tip{
  display: flex;
  align-items: center;
  height: 40px;
  margin-left: 70px;
  font-size: 12px;
}
</style>
